package com.hzdl.apple.dao.imp;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.hzdl.apple.bean.cart.CartItem;
import com.hzdl.apple.dao.CartDao;
import com.hzdl.apple.dao.BaseDaoImp;

public class CartDaoImp extends BaseDaoImp implements CartDao {

	@Override
	public void addCart(CartItem item) {

		sql = "insert into cartitem(CID,GoodsID,GoodsName,GoodsPrice,nums,AllPrice,UID,GoodsImg,GoodsColor,GoodsInch,IPadConn,MacDisc) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
		try {
		
			qr.update(sql, null, item.getGoodsID(), item.getGoodsName(), item.getGoodsPrice(), item.getNums(),item.getNums()*item.getGoodsPrice(),
					item.getUID(), item.getGoodsImg(), item.getGoodsColor(), item.getGoodsInch(), item.getIPadConn(),
					item.getMacDisc());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean exist(int GoodsID, int UID) {

		sql = "select * from cartitem where GoodsID=? and UID=?";
		try {	
			CartItem item = qr.query(sql, new BeanHandler<>(CartItem.class), GoodsID, UID);
			if (item != null) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return false;
	}

	@Override
	public boolean update(CartItem item) {

		sql = "update cartitem set nums=nums+1 where GoodsID=? and UID=?";
		try {
			qr.update(sql, item.getGoodsID(), item.getUID());
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public List<CartItem> getCarts(int UID) {

		sql = "select *,(GoodsPrice*nums) AllPrice from cartitem where UID=?";

		try {
			return qr.query(sql, new BeanListHandler<>(CartItem.class), UID);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	@Override
	public boolean update(int nums, int id) {
		sql = "update cartitem set nums=? where CID=?";
		try {
			int c = qr.update(sql, nums, id);
			if (c != 0) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean deleteCartById(int id) {
		sql = "delete from cartitem where CID=?";
		try {
			int c = qr.update(sql, id);
			if (c != 0) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void deleteAll(int UID, Connection conn) {
		sql = "delete from cartitem where UID=?";
		try {
			qr.update(conn, sql, UID);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
